package com.mop.core.es.dao.util;

import com.alibaba.fastjson.JSONObject;
import com.lemon.core.common.lang.util.Assert;
import com.lemon.core.common.lang.util.StringUtils;
import com.mop.core.es.dao.plugins.index.FieldType;
import com.mop.core.es.dao.plugins.index.MappingField;

import java.util.List;

/**
 * @author lemon
 * @ClassName MappingUtils
 * @desc mapping工具类
 * @Date 2019/3/1 10:16
 * @Version 1.0
 **/
public class MappingUtils {

    public static JSONObject buildSingleField(MappingField mappingField) {
        Assert.hasLength(mappingField.getFieldName(), "字段名称不可为空!");
        Assert.notNull(mappingField.getFieldType(), "字段类型不可为空!");

        JSONObject fieldObj = new JSONObject();
        fieldObj.put("type", mappingField.getFieldType().getTypeName());
        if (StringUtils.isNotBlank(mappingField.getIndex())) {
            fieldObj.put("index", mappingField.getIndex());
        }
        if (StringUtils.isNotBlank(mappingField.getAnalyzer())) {
            fieldObj.put("analyzer", mappingField.getAnalyzer());
        }
        if (StringUtils.isNotBlank(mappingField.getSearchAnalyzer())) {
            fieldObj.put("search_analyzer", mappingField.getSearchAnalyzer());
        }
        if (StringUtils.isNotBlank(mappingField.getFormat())) {
            fieldObj.put("format", mappingField.getFormat());
        }

        JSONObject wrapObj = new JSONObject();
        wrapObj.put(mappingField.getFieldName(), fieldObj);
        return wrapObj;
    }

    public static JSONObject buildMultiField(String fieldName, MappingField... mappingFields) {
        Assert.hasLength(fieldName, "字段名称不可为空!");
        Assert.notEmpty(mappingFields, "字段集合长度不可为0!");

        JSONObject wrapObj = new JSONObject();
        JSONObject listObj = new JSONObject();
        JSONObject propObj = new JSONObject();
        for (MappingField mappingField : mappingFields) {
            JSONObject fieldObj = MappingUtils.buildSingleField(mappingField);
            propObj.putAll(fieldObj);
        }
        listObj.put("properties", propObj);
        wrapObj.put(fieldName, listObj);
        return wrapObj;
    }
}
